package c926.xiaoduyun.xiaodu.plugin.other;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.util.io.ByteArrayOutputStream;
import kd.sdk.plugin.Plugin;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 动态表单插件
 */
public class PdfPrintTestPlugin extends AbstractFormPlugin implements Plugin {

    private static final String PDF_BUTTON_KEY = "c926_getpdf"; // 生成PDF附件按钮标识
    private static final String PDF_PRTPL_KEY = "c926_xiaoduapply_prtpl"; // PDF模版编码
    private static final String ATTACHMENT_PANEL_KEY = "attachmentpanel"; // PDF附件面板标识
    private static final String BILL_KEY = "c926_xiaoduapply"; // 单据标识

    @Override
    public void registerListener(EventObject e) {
        // 工具栏项注册点击监听
        Toolbar toolbar = this.getView().getControl("tbmain");
        toolbar.addItemClickListener(this);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        //点击生成打印模板附件
        if (PDF_BUTTON_KEY.equals(evt.getItemKey())) {
            DynamicObject source = this.getModel().getDataEntity(true);
            //1.根据模板生成附件
            //通过模版编码获取模版ID
            String tplId = BosPrintServiceHelper.getTplIdByNum(PDF_PRTPL_KEY);
            //构造打印服务接口需要的参数 PrintWork
            PrintWork work = new PrintWork();
            //设置打印语言
            work.setPrintLang("zh_CN");
            //设置类型：1代表pdf
            work.setExpType("1");
            List<PrintTask> printTasks = new ArrayList<>();
            PrintTask printTask = new PrintTask();
            printTask.setTplId(tplId);//设置模板ID
            //获取当前单据PKID
            Object id = this.getModel().getValue("id");
            //设置当前单据PKID
            printTask.setPkIds(new ArrayList<>(Collections.singletonList(id)));
            printTasks.add(printTask);
            work.setTaskList(printTasks);
            //调用打印服务接口
            PrtAttach doPrint = BosPrintServiceHelper.doPrint(work);
            List<PrtAttach.AttachDetail> attachDetails = doPrint.getAttachDetail();
            PrtAttach.AttachDetail attachDetail = attachDetails.get(0);
            // 将文件保存到附件
            List<Map<String, Object>> atts = new ArrayList<>();
            atts.add(createAttInfo(attachDetail));
            //上传附件到采购订单的附件面板中
            AttachmentServiceHelper.upload(BILL_KEY, source.getPkValue(), ATTACHMENT_PANEL_KEY, atts);
            this.getView().updateView();
            this.getView().showSuccessNotification("操作成功");
        }
    }


    //构建附件面板信息
    private Map<String, Object> createAttInfo(PrtAttach.AttachDetail attachDetail) {

        Map<String, Object> att = new HashMap<>();
        // 当前时间戳
        long time = new Date().getTime();
        // 创建一个SimpleDateFormat对象，并设置日期时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        // 获取当前日期时间，并格式化为字符串
        String currentTime = sdf.format(new Date());
        att.put("createdate", time);
        // lastModified:时间戳
        att.put("lastModified", time);
        att.put("status", "success");
        String attType = attachDetail.getFileType();
        att.put("type", attType);
        // name:文件名(含文件格式)
        att.put("name", currentTime + attachDetail.getFileName());
        FileService fs = FileServiceFactory.getAttachmentFileService();
        InputStream in = fs.getInputStream(attachDetail.getFilePath());
        try {
            // 附件大小
            byte[] AttByte = InputStreamToByte(in);
            att.put("size", AttByte.length);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        StringBuffer uid = new StringBuffer();
        uid.append("rc-upload-");
        uid.append(time);
        uid.append("-");
        uid.append("1");
        att.put("uid", uid.toString());
        att.put("url", attachDetail.getFilePath());
        return att;
    }

    // ImputStream输入流转二进制数据
    public byte[] InputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            bytestream.write(ch);
        }
        byte[] imgdata = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }


}